<?php
class News_model extends CI_Model{
	var $table = 'news';
	var $items = array('title','intro','content','category_id','source');
    
    function escape($data)
	{
		foreach($this->items as $k)
		{
			//$tmp[$k] = $this->db->escape_str($data[$k]);
            $tmp[$k] = $data[$k];
		}
        
        $tmp['title'] = strip_tags($tmp['title']);
        $tmp['created'] = date('Y-m-d H:i:s');
        preg_match('/<img.*?src="(.*?)"/i',$tmp['intro'],$match);
        if(preg_match('/<img.*?src="(.*?)"/i',$tmp['intro'],$match))
            $tmp['intro_thumb'] = $match[1];
        $tmp['intro'] = strip_tags($tmp['intro']);
		return $tmp;
	}
    
    function postnews($data)
    {
        $post = $this->escape($data);
        if(!empty($data['id']))
        {
            $where = 'id = "'.$data['id'].'"';
            $str = $this->db->update_string($this->table,$post,$where);
            
        }else{
            $str = $this->db->insert_string($this->table, $post);
        }
        
        $this->db->query($str);
        if($this->db->affected_rows() > 0)
            echo 'Post news thanh cong :)';
        else
            echo 'error';
    }
    
    function get_list_category()
    {
        $query = $this->db->get('category');
        return $query->result_object();
    }
    
    function get_news($limit,$offset,$category_id = null)
    {
       
        $sql = "SELECT title,id,intro,intro_thumb,DATE_FORMAT(created,'%Y %M %D, %H:%i:%s') as created FROM ".$this->table;
        //$this->db->order_by('id','DESC');
        if($category_id > 0)
            //$query = $this->db->get_where($this->table,array('category_id',$category_id),$limit,$offset);
            $sql .= " WHERE category_id = ".$category_id; 
        $sql .= " ORDER by ? ? LIMIT ?,?";
        $query = $this->db->query($sql, array('id','DESC',$offset,$limit));
        return $query->result_object();
    }
    
    function get_item($id)
    {
        $query = $this->db->get_where($this->table,array('id' => $id));
        return $query->row_object(0);
    }
    
    function get_count_news($category = null)
    {
        if($category > 0)
            $query = $this->db->get_where($this->table,array('category_id' => $category));
        else
            $query = $this->db->get($this->table); 
            
        return $query->num_rows();
    }
    
}
?>